package com.huang.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelTest {

    public static void main(String[] args) throws Exception {
        other();
    }

    public static void read() throws Exception{
        RandomAccessFile aFile = new RandomAccessFile("D:\\temp\\1.txt", "rw");
        FileChannel inChannel = aFile.getChannel();
        //初始化读取空间
        ByteBuffer buf = ByteBuffer.allocate(480);
        //写入 buf中
        while (inChannel.read(buf) != -1) {
            //类似于flush()函数功能，将buffer里面的数据刷新出去
            buf.flip();

            while(buf.hasRemaining()){
                System.out.print((char) buf.get());
            }
            //转换成 写入buf
            buf.clear();
        }
        aFile.close();
    }

    public static void transferTo() throws Exception{
        FileInputStream fileInputStream  = new FileInputStream(new File("D:\\temp\\1.txt"));
        FileOutputStream fileOutputStream  = new FileOutputStream(new File("D:\\temp\\2.txt"));
        //得到fileInputStream的文件通道
        FileChannel fileChannelInput = fileInputStream.getChannel();
        //得到fileOutputStream的文件通道
        FileChannel fileChannelOutput = fileOutputStream.getChannel();

        //将input通道的数据，写入到Output通道
        fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
    }

    public static void other() throws Exception{
        File file = new File("D:\\temp\\1.txt");
        File outFile = new File("D:\\temp\\2.txt");
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(outFile);
        //通过文件流拿到通道
        FileChannel channelIn = fis.getChannel();
        FileChannel channelOut = fos.getChannel();
        //为Buffer分配50个字节的空间
        ByteBuffer buffer = ByteBuffer.allocate(50);
        while(channelIn.read(buffer) != -1) {
            //获取channel中的位置，这个位置应该是0
            System.out.println("通道的当前位置:"+channelIn.position());
            // public abstract int read(ByteBuffer dst) throws IOException;

            //从channel的position读取一系列字节到缓冲对象中.
            channelIn.read(buffer);
            //这边打印channel通道的当前位置(打印值为50)
            System.out.println("通道的当前位置:"+channelIn.position());
            //同时可以看一下这时候channel.size()返回值是什么.(文件大小)
            System.out.println("通道的size返回值:"+channelIn.size());
            System.out.println("buffer中的数据:"+buffer.toString());
            //更改buffer的模式--读模式.这时position变为limit，channel从buffer的0开始读到limit.
            buffer.flip();
            System.out.println("buffer中的数据:"+buffer.toString());
            //这样会清空buffer中的数据
            channelOut.write(buffer);
            //positon为0表示ByteBuffer中已经没有数据了
            System.out.println("buffer中的数据:"+buffer.toString());
            buffer.clear();
        }
    }


}
